package com.wuuxiang.i5xforyou.service.coupon.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wuuxiang.i5xforyou.common.consts.Consts;
import com.wuuxiang.i5xforyou.common.domain.ResultMsg;
import com.wuuxiang.i5xforyou.common.domain.Results;
import com.wuuxiang.i5xforyou.common.service.impl.BaseServiceImpl;
import com.wuuxiang.i5xforyou.feign.impl.FeignClientService;
import com.wuuxiang.i5xforyou.service.coupon.CouponService;
import com.wuuxiang.i5xforyou.utils.HttpUtil;
import com.wuuxiang.i5xforyou.vo.coupon.ShopInfo;
import com.wuuxiang.i5xforyou.vo.kanjia.Coupon;

/** 
 * @ClassName: CouponServiceImpl <br/>
 * 砍价卷相关接口 <br/>
 * @author Mobile Web Group-lff
 * @date 2018年3月16日 下午6:02:04
 *
 */
@Service("couponService")
public class CouponServiceImpl extends BaseServiceImpl implements CouponService {

	@Autowired
	private FeignClientService feignClientService;
	
	/**
	 * Description: 获取本活动下我的优惠卷列表
	 * @author: Mobile Web Group-lff
	 * @date: 2018年3月19日 上午11:33:00
	 * 
	 * @see com.wuuxiang.i5xforyou.service.coupon.CouponService#getCoupons(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public ResultMsg getCoupons(String mpId, String openId, String campaignId, String crmVersion) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		params.put("mpId", mpId);
		params.put("openId", openId);
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				//入参
				params.put("campaignId", campaignId);
				//调用接口
				url = Consts.CLOUD_API_URL + "rest/marketing/campaignbargin/ticketList";
				resultJson = HttpUtil.doPostJSONObject(url, params.toJSONString());
				if (resultJson.getIntValue("returnCode") != 1 || !"200".equals(resultJson.getString("errorCode"))) {
					//失败
					log.error("获取砍价活动券列表失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("errorMsg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				//活动列表
				Coupon[] coupons = JSON.toJavaObject(resultJson.getJSONArray("coupons"), Coupon[].class);
				resultMsg.setMsgEntity(coupons);
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				JSONObject data = new JSONObject();
				data.put("campaignId", campaignId);
				data.put("campaignTypeId", 18);//活动类型，18:砍价活动
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/marketing/campaignBargain/listCoupons";
				//调用crm7接口获取本活动下我的优惠卷列表
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				if (resultJson.getIntValue("code") != 200) {
					//失败
					log.error("获取砍价活动券列表失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				//活动列表:jsonArray转List<Coupon>
				resultMsg.setMsgEntity(toCouponListForCrm7ListCoupons(resultJson.getJSONArray("content")));
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("获取砍价活动券列表失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
	//jsonArray转List<Coupon>
	private List<Coupon> toCouponListForCrm7ListCoupons(JSONArray content) {
		List<Coupon> coupons = new ArrayList<Coupon>();
		if (content != null) {
			for (int i = 0; i < content.size(); i++) {
				JSONObject couponJson = content.getJSONObject(i);
				Coupon coupon = new Coupon();
				coupon.setId(couponJson.getInteger("id"));//券标识
				coupon.setExpiryStart(couponJson.getString("startDate"));//券有效期开始日期
				coupon.setExpiryEnd(couponJson.getString("endDate"));//券有效期结束日期
				coupon.setCount(couponJson.getInteger("amount"));//数量
				coupon.setTitle(couponJson.getString("title"));//券标题
				coupon.setType(couponJson.getInteger("type"));//优惠券类型 0:全部 1:代金券 2:折扣券 3:品项券
				coupon.setValue(couponJson.getString("value"));//券金额
				coupon.setThreshold(couponJson.getBigDecimal("threshold"));//消费门槛
				
				coupons.add(coupon);
			}
		}
		return coupons;
	}

	/**
	 * Description: 获取优惠卷详情
	 * @author: Mobile Web Group-lff
	 * @date: 2018年3月19日 下午2:07:40
	 * 
	 * @see com.wuuxiang.i5xforyou.service.coupon.CouponService#getCouponDetail(java.lang.String, java.lang.String, com.wuuxiang.i5xforyou.vo.kanjia.Coupon)
	 */
	@Override
	public ResultMsg getCouponDetail(String mpId, String openId, Coupon coupon, String crmVersion) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		params.put("mpId", mpId);
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				//入参
				params.put("id", coupon.getId());
				//调用接口
				url = Consts.CLOUD_API_URL + "rest/marketing/campaignbargin/ticketKindDetail";
				resultJson = HttpUtil.doPostJSONObject(url, params.toJSONString());
				if (resultJson.getIntValue("returnCode") != 1 || !"200".equals(resultJson.getString("errorCode"))) {
					//失败
					log.error("获取砍价活动优惠卷详情失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("errorMsg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				//优惠卷详情
				Coupon resultCoupon = JSON.toJavaObject(resultJson, Coupon.class);
				//以入参的字段数据为主，将入参数据覆盖到返回结果
				rewriteCoupon(resultCoupon, coupon);
				
				resultMsg.setMsgEntity(resultCoupon);
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				params.put("openId", openId);
				JSONObject data = new JSONObject();
				data.put("couponId", coupon.getId());
				data.put("couponType", coupon.getType());
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/coupon/detail";
				//调用crm7接口查询获取优惠卷详情
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				if (resultJson.getIntValue("code") != 200) {
					//失败
					log.error("获取砍价活动优惠卷详情失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				//优惠卷详情
				Coupon resultCoupon = toCouponForCrm7CouponDetail(resultJson.getJSONObject("content"), mpId);
				//以入参的字段数据为主，将入参数据覆盖到返回结果
				rewriteCoupon(resultCoupon, coupon);
				
				resultMsg.setMsgEntity(resultCoupon);
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("获取砍价活动优惠卷详情失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
	//JSONObject转Coupon
	private Coupon toCouponForCrm7CouponDetail(JSONObject couponJson, String mpId) {
		if (couponJson == null) {
			return new Coupon();
		}
		//JSONObject转Coupon
		Coupon coupon = JSON.toJavaObject(couponJson, Coupon.class);
		//适用门店限制(0:无限制,1:有限制),crm7都是有限制
		coupon.setUseSubShopLimit(1);
		JSONArray shopsArray = couponJson.getJSONArray("suitableShops");
		List<ShopInfo> subShopList = new ArrayList<ShopInfo>();
		if (shopsArray != null) {
			//先获取云端的门店信息
			Map<Integer, ShopInfo> o2oShopInfoMap = feignClientService.getShops(mpId);
			//根据crm的门店id获取云端的门店信息，因为crm的门店电话等信息都不一定对，以云端的信息为准
			for (int i = 0; i < shopsArray.size(); i++) {
				ShopInfo o2oShopInfo = o2oShopInfoMap.get(shopsArray.getJSONObject(i).getInteger("mcId"));
				if (o2oShopInfo != null) {
					subShopList.add(o2oShopInfo);
				}
			}
		}
		coupon.setSubShopList(subShopList);
		
		return coupon;
	}
	
	//以入参的字段数据为主，将入参数据覆盖到返回结果
	private void rewriteCoupon(Coupon resultCoupon, Coupon inputCoupon) {
		if (inputCoupon.getId() != null) {
			resultCoupon.setId(inputCoupon.getId());//券类型id
		}
		if (StringUtils.isNotBlank(inputCoupon.getExpiryStart())) {
			resultCoupon.setExpiryStart(inputCoupon.getExpiryStart());//优惠券有效期开始日期
		}
		if (StringUtils.isNotBlank(inputCoupon.getExpiryEnd())) {
			resultCoupon.setExpiryEnd(inputCoupon.getExpiryEnd());//优惠券有效期结束日期
		}
		if (StringUtils.isNotBlank(inputCoupon.getTitle())) {
			resultCoupon.setTitle(inputCoupon.getTitle());//券标题
		}
		if (inputCoupon.getType() != null) {
			resultCoupon.setType(inputCoupon.getType());//优惠券类型( 1:代金券 3:品项券)	
		}
		if (StringUtils.isNotBlank(inputCoupon.getValue())) {
			resultCoupon.setValue(inputCoupon.getValue());//代金券面值
		}
		if (inputCoupon.getThreshold() != null) {
			resultCoupon.setThreshold(inputCoupon.getThreshold());//消费门槛
		}
	}
	/**
	 * Description: 获取砍价赠券
	 * @author: Mobile Web Group-LiuYandong
	 * @date: 2018年3月19日 下午2:07:40
	 */
	@Override
	public ResultMsg getGiftCoupon(String mpId, String openId, String initiatorOpenId, Long campaignId, String couponId, String crmVersion) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				//调用接口
				StringBuilder urlCrm6 = new StringBuilder(Consts.CRM6_WEBSERVICE_URL);
				urlCrm6.append("WeiXinTicketResult&activityType=10");
				urlCrm6.append("&ticketkind=").append(couponId);
				urlCrm6.append("&marketActivityID=").append(campaignId);
				urlCrm6.append("&openId=").append(openId);
				urlCrm6.append("&weixinPlatID=").append(mpId);
				urlCrm6.append("&initiatorOpenId=").append(initiatorOpenId);
				urlCrm6.trimToSize();
				//统一url，为了catch中输出log
				url = urlCrm6.toString();
				
				resultJson = HttpUtil.doGetJSONObject(url);
				int v_card_error_code = resultJson.getIntValue("v_error_code");
				if (v_card_error_code == 0) {
					
				}else {
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("v_error_msg")));
					log.error("领取砍价赠送优惠卷失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				params.put("mpId", mpId);
				params.put("openId", openId);
				JSONObject data = new JSONObject();
				data.put("initiatorOpenId", initiatorOpenId);
				data.put("campaignId", campaignId);
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/marketing/campaignBargain/sendCoupon";
				//调用crm7接口查询获取优惠卷详情
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				if (resultJson.getIntValue("code") != 200) {
					//失败
					log.error("领取砍价赠送优惠卷失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("获取砍价活动优惠卷详情失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setException(e);
			return resultMsg;
		}
	}

	/**
	 * Description: 购买优惠卷
	 * @author: Mobile Web Group-lff
	 * @date: 2018年3月21日 下午1:16:01
	 * 
	 * @see com.wuuxiang.i5xforyou.service.coupon.CouponService#buyCoupon(java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.wuuxiang.i5xforyou.vo.kanjia.Coupon)
	 */
	@Override
	public ResultMsg buyCoupon(String mpId, String openId, String campaignId, Coupon coupon, String crmVersion, String crm7Code, String appId) {
		/*
		 * 1,预购买接口---->出参金额>0---->云端支付--->确认购买接口
		 * 2,预购买接口---->出参金额=0---->确认购买接口
		 * resultMsg.flag:0成功（代表购买金额>0）唤起收银台，1成功（代表购买金额=0），-1失败, -2库存量不足失败
		 */
		//预购买
		ResultMsg resultMsg = preBuyCoupon(mpId, openId, campaignId, coupon, crmVersion, crm7Code);
		if (resultMsg.getState() == Results.ERROR) {
			//失败
			return resultMsg;
		}
		
		//预购买成功
		JSONObject preBuyResult = (JSONObject) resultMsg.getMsgEntity();
		String buyPrice = preBuyResult.getString("buyPrice");
		if (StringUtils.isNotBlank(buyPrice) && new BigDecimal(buyPrice).compareTo(BigDecimal.ZERO) > 0) {
			//购买金额不为0的时候，提交云端下单接口
			return commPaySubmit(mpId, openId, preBuyResult, crmVersion, appId);
		} else {
			//购买金额为0的时候，直接回调确认购买接口
			return confirmBuyCoupon(mpId, openId, preBuyResult, crmVersion);
		}
	}
	
	//预购买
	private ResultMsg preBuyCoupon(String mpId, String openId, String campaignId, Coupon coupon, String crmVersion, String crm7Code) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				StringBuilder urlCrm6 = new StringBuilder(Consts.CRM6_WEBSERVICE_URL);
				urlCrm6.append("WeiXinTicketResult");
				urlCrm6.append("&activityType=").append(10);//10:砍价活动
				urlCrm6.append("&ticketkind=").append(coupon.getId());
				urlCrm6.append("&marketActivityID=").append(campaignId);
				urlCrm6.append("&openId=").append(openId);
				urlCrm6.append("&weixinPlatID=").append(mpId);
				urlCrm6.append("&sendCount=").append(coupon.getCount());
				urlCrm6.append("&initiatorOpenId=").append(openId);//砍价活动发起人微信id
				urlCrm6.trimToSize();
				//统一url，为了catch中输出log
				url = urlCrm6.toString();
				
				//调用接口
				resultJson = HttpUtil.doGetJSONObject(url);
				int v_error_code = resultJson.getIntValue("v_error_code");
				if (v_error_code == 1004) {
					//库存不足
					log.error("预购买砍价优惠卷失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setFlag(-2);//-2代表库存不足
					resultMsg.setException(new Exception(resultJson.getString("v_error_msg")));
					//将库存量返回去
					JSONObject responseJson = new JSONObject();
					responseJson.put("stockNum", resultJson.getInteger("v_can_buy_count"));
					resultMsg.setMsgEntity(responseJson);
					return resultMsg;
				}
				if (v_error_code != 0) {
					//其它失败
					log.error("预购买砍价优惠卷失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setFlag(-1);//-1代表其它失败
					resultMsg.setException(new Exception(resultJson.getString("v_error_msg")));
					return resultMsg;
				}
				//预购买成功
				resultMsg.setState(Results.SUCCESS);
				JSONObject preBuyResult = new JSONObject();
				preBuyResult.put("mcId", resultJson.getString("v_mc_id"));
				preBuyResult.put("buyPrice", resultJson.getString("v_buy_price"));
				preBuyResult.put("orderNo", resultJson.getString("v_ticket_no"));
				resultMsg.setMsgEntity(preBuyResult);
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				params.put("mpId", mpId);
				params.put("openId", openId);
				JSONObject data = new JSONObject();
				data.put("orderNo", crm7Code);//crm7的流水号
				data.put("campaignId", campaignId);
				data.put("campaignTypeId", 18);//活动类型，18:砍价活动
				String appCaller = getApiCaller();
				if (WEI_XIN.equals(appCaller) || XIAO_CHENG_XU.equals(appCaller)){
					data.put("payTypeId", 6);//支付类型 6微信8支付宝
				}
				if (ZHI_FU_BAO.equals(appCaller)){
					data.put("payTypeId", 8);//支付类型 6微信8支付宝
				}
				//购买的券信息
				JSONArray couponArray = new JSONArray();
				JSONObject couponJson = new JSONObject();
				couponJson.put("couponId", coupon.getId());
				couponJson.put("couponNum", coupon.getCount());
				couponJson.put("couponType", coupon.getType());
				couponJson.put("couponMoney", coupon.getMoney());
				couponArray.add(couponJson);
				data.put("couponBuys", couponArray);
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/marketing/preBuy";
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				if (resultJson.getIntValue("code") != 200) {
					//先判断是不是库存不足的失败
					JSONArray couponStock = resultJson.getJSONObject("content").getJSONArray("couponStock");//券库存信息
					if (couponStock != null) {
						Integer currStock = couponStock.getJSONObject(0).getInteger("currStock");
						if (currStock != null && coupon.getCount() != null && currStock < coupon.getCount()) {
							//库存不足
							log.error("预购买砍价优惠卷失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
							resultMsg.setState(Results.ERROR);
							resultMsg.setFlag(-2);//-2代表库存不足
							resultMsg.setException(new Exception(resultJson.getString("msg")));
							//将库存量返回去
							JSONObject responseJson = new JSONObject();
							responseJson.put("stockNum", currStock);
							resultMsg.setMsgEntity(responseJson);
							return resultMsg;
						}
					}
					//失败
					log.error("预购买砍价优惠卷失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setFlag(-1);//-1代表其它失败
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				JSONObject resultContentJson = resultJson.getJSONObject("content");
				JSONObject preBuyResult = new JSONObject();
				preBuyResult.put("mcId", resultContentJson.getString("shopId"));
				preBuyResult.put("buyPrice", resultContentJson.getString("buyMoney"));
				preBuyResult.put("orderNo", crm7Code);
				resultMsg.setMsgEntity(preBuyResult);
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setFlag(-1);//-1代表其它失败
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("预购买砍价优惠卷失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setFlag(-1);//-1代表其它失败
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
	//提交云端下单
	private ResultMsg commPaySubmit(String mpId, String openId, JSONObject preBuyResult, String crmVersion, String appId) {
		ResultMsg resultMsg = new ResultMsg();
		//入参
		JSONObject commPayParams = new JSONObject();
		commPayParams.put("orderid", preBuyResult.getString("orderNo"));
		commPayParams.put("cardinfo", new JSONArray());
		commPayParams.put("money", preBuyResult.getString("buyPrice"));
		commPayParams.put("trueMoney", preBuyResult.getString("buyPrice"));
		commPayParams.put("payMoney", preBuyResult.getString("buyPrice"));
		commPayParams.put("kind", "10325");
		commPayParams.put("storeid", preBuyResult.getString("mcId"));
		commPayParams.put("paySerialNo", "");
		commPayParams.put("payBusinNo", preBuyResult.getString("orderNo"));
		commPayParams.put("paytypeid", 6);
		String appCaller = getApiCaller();
		if (WEI_XIN.equals(appCaller)){
			commPayParams.put("payFrom", 3);
		} else if (XIAO_CHENG_XU.equals(appCaller)){
			//小程序payFrom和微信一样
			commPayParams.put("payFrom", 3);
			//单独加了一个payTypeProd字段
			commPayParams.put("payTypeProd", "miniProgram");
		} else if (ZHI_FU_BAO.equals(appCaller)){
			commPayParams.put("payFrom", 6);
		}
		commPayParams.put("body", "购买券");

		JSONArray goods = new JSONArray();
		JSONObject good = new JSONObject();
		good.put("goodsName", "购买券");
		good.put("price", preBuyResult.getString("buyPrice"));
		good.put("quantity", "1");
		goods.add(good);
		commPayParams.put("goods", goods);
		
		// 完成购买后的核销链接
		String udStateUrl = "";
		if (Consts.CRM6.equals(crmVersion)) {
			udStateUrl = Consts.CRM6_WEBSERVICE_URL + "WeiXinUpdateTicketInfo";
		} else if (Consts.CRM7.equals(crmVersion)) {
			udStateUrl = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "o2o/coupon/confirmBuy";
		}
		commPayParams.put("udStateUrl", udStateUrl);
		commPayParams.put("turnUrl", "");
		commPayParams.put("ishdfk", 0);
		commPayParams.put("openid", openId);
		//commonpayParams.put("unionid", unionId); //20170207应对支付宝新接口升级增加支付宝UnionId
		commPayParams.put("mpid", mpId);
		commPayParams.put("busiScopeNo", "buyTicket");
		//commonpayParams.put("chongzhiUrl", chongzhiUrl);
		commPayParams.put("appid", appId);
		//commPayParams.put("parentOpenid", getSessionOAuth2ParentAccessToken().getOpenid());//支付父账号openid
		//入参
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("data", commPayParams.toJSONString());
		//url
		String url = Consts.CLOUD_API_URL + "pay/CommPaySubmit.htm";
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			//提交通用支付
			resultJson = HttpUtil.doPostJSONObject(url, params);
			if (resultJson.getIntValue("returnCode") != 1 || !"200".equals(resultJson.getString("errorCode"))){
				// 记录log
				log.error("购买砍价优惠卷,提交通用支付接口出错，" + "url:" + url + ",params=" + params + ",result=" + resultJson);
				resultMsg.setState(Results.ERROR);
				resultMsg.setFlag(-1);//-1代表其它失败
				resultMsg.setException(new Exception(resultJson.getString("errorText")));
				return resultMsg;
			}
			// 不用就先注释掉吧，要不也会费内存
			// String payUrl = getFullUrl(ConfigConstants.CLOUD_API_URL + "tcsl/pay.html", "key=" + rstJson.getString("key"), "envType=" + rstJson.getString("envType"));
			resultMsg.setState(Results.SUCCESS);
			resultMsg.setFlag(0);//0成功（代表购买金额>0）唤起收银台
			JSONObject commPayResult = new JSONObject();
			commPayResult.put("key", resultJson.getString("key"));
			commPayResult.put("envType", resultJson.getString("envType"));
			resultMsg.setMsgEntity(commPayResult);
			return resultMsg;
		} catch (Exception e) {
			log.error("购买砍价优惠卷,提交通用支付接口出错，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setFlag(-1);//-1代表其它失败
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
	
	//确认购买,购买金额=0时才会走这个方法
	private ResultMsg confirmBuyCoupon(String mpId, String openId, JSONObject preBuyResult, String crmVersion) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				StringBuilder urlCrm6 = new StringBuilder(Consts.CRM6_WEBSERVICE_URL);
				urlCrm6.append("WeiXinUpdateTicketInfo");
				urlCrm6.append("&orderid=").append(preBuyResult.getString("orderNo"));//流水号
				urlCrm6.trimToSize();
				//统一url，为了catch中输出log
				url = urlCrm6.toString();
				
				//调用接口
				resultJson = HttpUtil.doGetJSONObject(url);
				if (resultJson.getIntValue("returnCode") != 1 || !"200".equals(resultJson.getString("errorCode"))) {
					//失败
					log.error("确认购买砍价优惠卷失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setFlag(-1);//-1代表其它失败
					resultMsg.setException(new Exception(resultJson.getString("errorText")));
					return resultMsg;
				}
				//确认购买成功
				resultMsg.setState(Results.SUCCESS);
				resultMsg.setFlag(1);//1成功（代表购买金额=0）
				resultMsg.setMsg(resultJson.getString("errorText"));
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				params.put("mpId", mpId);
				params.put("openId", openId);
				JSONObject data = new JSONObject();
				data.put("orderid", preBuyResult.getString("orderNo"));//预充值流水号（CRM7流水号）
				data.put("storeid", preBuyResult.getString("mcId"));
				String appCaller = getApiCaller();
				if (WEI_XIN.equals(appCaller) || XIAO_CHENG_XU.equals(appCaller)){
					data.put("payTypeId", 6);//支付类型 6微信8支付宝
				}
				if (ZHI_FU_BAO.equals(appCaller)){
					data.put("payTypeId", 8);//支付类型 6微信8支付宝
				}
				data.put("paymoney", preBuyResult.getString("buyPrice"));
				//data.put("ordno", null);//云端支付流水,金额为0的时候，不走云端下单，所以无云端支付
				data.put("tradeState", 0);//支付结果 0：成功 其他：失败
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/marketing/confirmBuy";
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				if (resultJson.getIntValue("code") != 200) {
					//失败
					log.error("确认购买砍价优惠卷失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setFlag(-1);//-1代表其它失败
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//确认购买成功
				resultMsg.setState(Results.SUCCESS);
				resultMsg.setFlag(1);//1成功（代表购买金额=0）
				resultMsg.setMsg(resultJson.getString("errorText"));
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setFlag(-1);//-1代表其它失败
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("确认购买砍价优惠卷，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setFlag(-1);//-1代表其它失败
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
}
